/**********************************************
                uart.c
                zhangtaolei   2016-6-18
***********************************************/

/**********************************************
                include
***********************************************/
#include <stdarg.h>
#include <stdio.h>

#include "uart.h"

/**********************************************
                macro
***********************************************/

/**********************************************
                typedef
***********************************************/

/**********************************************
                variables
***********************************************/
#if UART2_PRINT
unsigned char g_PrintBuf[100] = {0};
#endif

ComFifo_t g_Uart2Comfifo;

/**********************************************
                functions
***********************************************/
void Uart2Init()
{
	GPIO_Init(GPIOD, GPIO_PIN_5, GPIO_MODE_IN_PU_NO_IT);
	GPIO_Init(GPIOD, GPIO_PIN_6, GPIO_MODE_IN_FL_NO_IT);
	InitComFifo(&g_Uart2Comfifo);
	UART2_Init(19200, UART2_WORDLENGTH_8D,UART2_STOPBITS_1,UART2_PARITY_NO,
	                    UART2_SYNCMODE_CLOCK_DISABLE, 
	                    UART2_MODE_TX_ENABLE|UART2_MODE_RX_ENABLE); 
	UART2_ITConfig(UART2_IT_RXNE_OR, ENABLE); 
	UART2_Cmd(ENABLE); 
}

void Uart2Send(uint8_t *buf, uint16_t len)
{
    uint16_t i = 0;
    for (i = 0; i < len; i++)
    {
        UART2_SendData8(buf[i]);
        while(!UART2_GetFlagStatus(UART2_FLAG_TC));
    }
}

void Uart2Irq(void)
{
	uint8_t c;
	if (UART2_GetFlagStatus(UART2_FLAG_RXNE) != RESET) {
		c = UART2_ReceiveData8();
		WriteComFifo(&g_Uart2Comfifo, &c, 1);
		UART2_ClearFlag(UART2_FLAG_RXNE);
	}
}

void Uart2Echo()
{
	uint8_t buf[8];
	uint8_t len;

	len = ReadComFifo(&g_Uart2Comfifo, buf, sizeof(buf));
	if (len)
	{
		Uart2Send(buf, len);;
	}
}


#if UART2_PRINT
void Uart2Print(const char *fmt, ...)
{
    unsigned short len;
    va_list ap;

    va_start(ap, fmt);
    len = vsprintf((char *)g_PrintBuf,(const char *)fmt,ap);
    va_end(ap);

    if(len > 100){
        len = 100;
    }

    Uart2Send(g_PrintBuf,len);
}
#endif

